const { renderFile, setDefaults, setFilter } = require("swig")
const { parse, stringify } = require("yaml")
const { readFileSync, readFile, readv, writeFile, existsSync, mkdirSync, writeFileSync } = require("fs")
const { resolve, basename, extname, dirname } = require("path")
const { mock } = require("mockjs")

function generateSql(tableName, arr) {
  if (arr && Array.isArray(arr)) {
    return arr.map(el => {
      const vals = Object.values(el).map(el => {
        if (typeof (el) == "string") {
          return `'${el}'`
        }
        return el;
      })
      return `insert into ${tableName} (${Object.keys(el).join(",")}) values (${vals.join(",")}) ;`
    }).join("\n")
  }
}

function process(pth, locals, cb) {

  try {
    // readFile(pth, { encoding: 'utf-8', signal: true }, function (err, data) {
    //   if (err) {
    //     throw err
    //   }
    // const locals = parse(data)
    const obj = {}
    let arr = undefined

    const { length, min, max, path, format, tableName } = locals.rootSetting

    if (length) {
      arr = obj["root|" + length] = [];
    } else {
      arr = obj["root|" + min + "," + max] = [];
    }
    arr[0] = {}

    const simpleMap = {
      color: {
        hex: "@hex()",
        rgb: "@rgb()",
        rgba: "@rgba()",
        hsl: "@hsl()"
      },
      address: {
        region: "@region()",
        province: "@province()",
        city: "@city()",
        county: "@county()",
        zip: "@zip()"
      },
      web: {
        url: "@url()",
        domain: "@domain()",
        protocol: "@protocol()",
        tld: "@tld()",
        email: "@email()",
        ip: "@ip()",
      },
      names: {
        first: "@first()",
        last: "@last()",
        name: "@name()",
        cfirst: "@cfirst()",
        clast: "@clast()",
        cname: "@cname()",
      },
      id: {
        guid: "@guid()",
        id: "@id()",
        increment: "@increment()"
      }
    }

    locals.propertys.forEach(p => {
      const [model, subModel] = p.type
      const simpleExpress = simpleMap[model] ? simpleMap[model][subModel] : undefined;
      const indexPath = resolve(__dirname, "./models", model, "index.js")

      if (!simpleExpress) {
        if (existsSync(indexPath)) {
          arr[0][p.name] = require(`./models/${model}/index.js`)(p)
        } else {
          arr[0][p.name] = require(`./models/${model}/${subModel}`)(p)
        }
      } else {
        arr[0][p.name] = simpleExpress
      }
    })

    const result = mock(obj)
    let content = undefined;
    if (format == "yaml") {
      content = stringify(Object.values(result)[0])
    } else if (tableName && format == "sql") {
      content = generateSql(tableName, Object.values(result)[0]);
    } else {
      content = JSON.stringify(Object.values(result)[0])
    }

    const outDir = dirname(path)
    if (!existsSync(outDir)) {
      mkdirSync(outDir, { recursive: true })
    }

    writeFileSync(path, content, { encoding: "utf-8" })
    cb(undefined, undefined)
    // })
  } catch (error) {
    cb(error, undefined)
  }



}

module.exports = {
  process
}